import { createResolvablePromise } from '@/utils/common'
import { showToast } from '@/utils/toast'
import {
  Button,
  Modal,
  ModalBody,
  ModalContent,
  ModalFooter,
  ModalHeader,
  useDisclosure,
} from '@heroui/react'
import { forwardRef, useImperativeHandle, useRef } from 'react'

interface Props {}
interface showParams {}

type ResolveType = {}

const title = 'Add Game'
const DefaultModal = (_props: Props, ref: any) => {
  const { isOpen, onOpen, onClose } = useDisclosure()
  const successResolve =
    useRef<(value: ResolveType | PromiseLike<ResolveType>) => void>(null)
  useImperativeHandle(ref, () => ({
    show: (_params: showParams) => {
      const [p, resolve] = createResolvablePromise<ResolveType>()
      successResolve.current = resolve

      // TODO: 根据参数渲染

      onOpen()
      return p
    },
  }))

  const onSubmit = () => {
    const data: ResolveType = {}

    successResolve.current(data)
    onClose()
    showToast('添加成功')
  }

  return (
    <Modal isOpen={isOpen} onClose={onClose} className="dark" size="4xl">
      <ModalContent>
        {(onClose) => {
          return (
            <>
              <ModalHeader>{title}</ModalHeader>
              <ModalBody></ModalBody>
              <ModalFooter>
                <Button
                  size="sm"
                  onPress={() => {
                    onClose()
                  }}>
                  取消
                </Button>
                <Button
                  size="sm"
                  color="primary"
                  style={{
                    color: 'white',
                  }}
                  onPress={() => {
                    onSubmit()
                  }}>
                  确定
                </Button>
              </ModalFooter>
            </>
          )
        }}
      </ModalContent>
    </Modal>
  )
}

export default forwardRef(DefaultModal)
